package com.winit.openapi.ups.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.ups.spi.systemrule.CityService;
import com.winit.ups.spi.systemrule.CountryService;
import com.winit.ups.spi.systemrule.DistrictService;
import com.winit.ups.spi.systemrule.StateService;
import com.winit.ups.spi.systemrule.command.CityCommand;
import com.winit.ups.spi.systemrule.command.CountryCheckedCommand;
import com.winit.ups.spi.systemrule.command.CountryCommand;
import com.winit.ups.spi.systemrule.command.DistrictCommand;
import com.winit.ups.spi.systemrule.command.StateCommand;
import com.winit.ups.spi.systemrule.vo.City;
import com.winit.ups.spi.systemrule.vo.Country;
import com.winit.ups.spi.systemrule.vo.District;
import com.winit.ups.spi.systemrule.vo.State;

/**
 * 国家省市区 <Change to the actual description of this class>
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * peipei.zeng 	1.0  		2015年6月5日 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/ups/addressdata")
public class CountryAddressController extends BaseController {

    @Resource
    private CountryService  countryService;
    @Resource
    private StateService    stateService;
    @Resource
    private CityService     cityService;
    @Resource
    private DistrictService districtService;

    /**
     * 根据countrycode获得省份
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/province")
    public String listProvinceByCountryCode(@ModelAttribute RequestMsg requestMsg,
                                            @ModelAttribute ResponseMsg responseMsg) {

        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        // 先根据countryCode获得countryId
        String countryCode = "";
        CountryCheckedCommand countryCommand = new CountryCheckedCommand();

        if (!isExistValue(json, "countryCode")) {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "countryCode");
        }
        countryCode = (String) json.get("countryCode");
        countryCommand.setCountryField(countryCode);
        List<Country> countryList = countryService.getCountryListByCodeOrName(countryCommand);
        if (null == countryList || countryList.size() <= 0) {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "countryCode");
        }
        // 再根据countryId获得省份信息
        long countryId = countryList.get(0).getCountryId();
        StateCommand command = new StateCommand();
        //为请求参数设置上下文
        command.setCtx(CommandContext.getContext());
        command.setCountryId(countryId);
        List<State> stateList = stateService.findStateList(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", stateList);
        responseMsg.setData(data);
        return SUCCESS;
    }

    /**
     * 根据provinceCode获得城市
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/city")
    public String listCityByProvinceCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        // 先根据provinceCode获得provinceId
        String provinceCode = "";
        StateCommand stateCommand = new StateCommand();

        if (!isExistValue(json, "provinceCode")) {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "provinceCode");
        }
        provinceCode = (String) json.get("provinceCode");
        stateCommand.setStateCode(provinceCode);
        List<String> listProvniceIds = stateService.getStateIdListLikeCode(stateCommand);
        if (null == listProvniceIds || listProvniceIds.size() <= 0) {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "countryCode");// TODO
        }
        // 再根据provinceId获得城市信息
        long provinceId = Long.parseLong(listProvniceIds.get(0));
        CityCommand command = new CityCommand();
        //为请求参数设置上下文
        command.setCtx(CommandContext.getContext());
        command.setStateId(provinceId);
        List<City> cityList = cityService.getCityByStateId(command);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", cityList);
        responseMsg.setData(data);
        return SUCCESS;
    }

    /**
     * 根据cityCode获得区域和邮编
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/district")
    public String listDistrictByCityCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        String cityCode = "";
        DistrictCommand districtCommand = new DistrictCommand();
        //为请求参数设置上下文
        districtCommand.setCtx(CommandContext.getContext());

        if (!isExistValue(json, "cityCode")) {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "cityCode");
        }
        cityCode = (String) json.get("cityCode");
        districtCommand.setCityCode(cityCode);
        List<District> districtList = districtService.getDistrictByCityCode(districtCommand);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", districtList);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    
    /**
     * 查询所有的国家
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/allCountry")
    public String queryAllCountrys(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	
    	CountryCommand countryCommand=new CountryCommand();
        //为请求参数设置上下文
        countryCommand.setCtx(CommandContext.getContext());      
    	List<Country>  countryList=countryService.getCountryList(countryCommand);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", countryList);
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    

    // 判断非必填字段是否有值
    public boolean isExistValue(JSONObject jsonObject, String key) {
    	if (jsonObject == null || jsonObject.getString(key) == null) {
    		return false;
    	}else{
            return !"".equals(jsonObject.getString(key).trim());
    	}
    }

}
